package com.example.demo.controller;

import java.util.Map;
import com.example.demo.entity.Role;
import com.example.demo.service.RoleService;
import com.example.demo.controller.vo.ResponseResult;
import com.example.demo.controller.vo.RoleSetRulesRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/admin/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @PostMapping
    public ResponseResult<Role> createRole(@RequestHeader("token") String token,
                                        @RequestParam String name,
                                        @RequestParam Integer status,
                                        @RequestParam String desc) {
        log.info("Creating new role: name={}, status={}", name, status);
        Role role = new Role();
        role.setName(name);
        role.setStatus(status);
        role.setDesc(desc);
        Role createdRole = roleService.createRole(role);
        log.info("Role created successfully: id={}", createdRole.getId());
        return ResponseResult.success(createdRole);
    }

    @PostMapping("/{id}")
    public ResponseResult<Role> updateRole(@RequestHeader("token") String token,
                                        @PathVariable Integer id,
                                        @RequestParam String name,
                                        @RequestParam Integer status,
                                        @RequestParam String desc) {
        log.info("Updating role: id={}, name={}, status={}", id, name, status);
        Role role = new Role();
        role.setId(id);
        role.setName(name);
        role.setStatus(status);
        role.setDesc(desc);
        Role updatedRole = roleService.updateRole(role);
        log.info("Role updated successfully: id={}", updatedRole.getId());
        return ResponseResult.success(updatedRole);
    }

    @PostMapping("/{id}/delete")
    public ResponseResult<Boolean> deleteRole(@RequestHeader("token") String token,
                                           @PathVariable Integer id) {
        log.info("Deleting role: id={}", id);
        boolean result = roleService.deleteRole(id);
        if (result) {
            log.info("Role deleted successfully: id={}", id);
        } else {
            log.warn("Failed to delete role: id={}", id);
        }
        return ResponseResult.success(result);
    }

    @GetMapping("/{page}")
    public ResponseResult<?> getRoleList(@RequestHeader("token") String token,
                                       @PathVariable Integer page,
                                       @RequestParam(defaultValue = "10") Integer limit,
                                       @RequestParam(required = false) String keyword) {
        log.info("Fetching role list: page={}, limit={}, keyword={}", page, limit, keyword);
        Object result = roleService.getRoleList(page, limit, keyword);
        log.debug("Fetched {} roles", result instanceof Map ? ((Map<?, ?>) result).size() : "unknown");
        return ResponseResult.success(result);
    }

    @PostMapping("/{id}/update_status")
    public ResponseResult<Boolean> updateRoleStatus(@RequestHeader("token") String token,
                                                 @PathVariable Integer id,
                                                 @RequestParam Integer status) {
        log.info("Updating role status: id={}, new_status={}", id, status);
        boolean result = roleService.updateRoleStatus(id, status);
        if (result) {
            log.info("Role status updated successfully: id={}", id);
        } else {
            log.warn("Failed to update role status: id={}", id);
        }
        return ResponseResult.success(result);
    }

    @PostMapping("/set_rules")
    public ResponseResult<Boolean> setRules(@RequestHeader("token") String token,
                                         @RequestBody RoleSetRulesRequest request) {
        log.info("Setting rules for role: id={}, rule_ids={}", request.getId(), request.getRule_ids());
        boolean result = roleService.setRules(request.getId(), request.getRule_ids());
        if (result) {
            log.info("Rules set successfully for role: id={}", request.getId());
        } else {
            log.warn("Failed to set rules for role: id={}", request.getId());
        }
        return ResponseResult.success(result);
    }

    @GetMapping("/all")
    public ResponseResult<?> getAllActiveRoles(@RequestHeader("token") String token) {
        log.info("Fetching all active roles");
        List<Map<String, Object>> roles = roleService.getAllActiveRoles();
        Map<String, Object> result = new HashMap<>();
        result.put("roles", roles);
        log.debug("Fetched {} active roles", roles.size());
        return ResponseResult.success(result);
    }
}
